import gobject
import Sysaccess

class Mtab:
    def __init__(self,controller):
        self.controller = controller
        self.mtab = None
        self.used_mount_points = None
        self.mounted_shares = None
        self.refresh()
        
    def refresh(self):
        
        self.mtab = []
        self.used_mount_points = []
        self.mounted_shares = {}
        
        self.mtab = Sysaccess.get_mtab()
        for item in self.mtab:
            self.used_mount_points.append(item[1].rstrip('/'))
            if item[2] in ('cifs','fuse.sshfs','fuse'):
                share = self.find(item[0],item[2])
                if share:
                    share.mount_label = item[0] # <--- Useless ?
                    self.mounted_shares[share] = item[1]
        
        for share_id,share in self.controller.shares:
            if share in self.mounted_shares:  
                self.controller.shares.set_mounted(share,True)
            else:
                self.controller.shares.set_mounted(share,False)
        
    def find(self,fslabel,type):
        if type == 'cifs':
            split = fslabel.strip('/').split('/')
            server = split[0]
            del split[0]
            path = '/'
            for item in split:
                path += item + '/'
            return self.controller.shares.get_share_by_addr(server.lower(),path)
        elif type == 'fuse.sshfs':
            srv,path = fslabel.split(':')
            user,server = srv.split('@')
            return self.controller.shares.get_share_by_addr(server.lower(),path)
        elif type == 'fuse' and fslabel.find('curlftpfs#ftp://') != -1:
            pass
    
    def get_current_mount_point(self,share):
        # retourner un tableau
        for item,mount_point in self.mounted_shares.iteritems():
            if share == item:
                return mount_point
    
    def get_current_share(self,mount_point):
        for item,mount_point in self.mounted_shares.iteritems():
            if mount_point.rstrip('/') == mount_point.rstrip('/'):
                return item